﻿using MediatR;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Domains.WarehouseCommon;
using ERPSystem.Common.Infrastructure.IRepository;

namespace BasicInformationCommon.API.BasicInformationCommons.ArrivalTypees
{
    public class ArrivalTypeQueryHandler : IRequestHandler<ArrivalTypeQueryCommand, Result>
    {
        private readonly IBaseRepository<ArrivalType> _arrivalTypeRepository;

        public ArrivalTypeQueryHandler(IBaseRepository<ArrivalType> arrivalTypeRepository)
        {
            _arrivalTypeRepository = arrivalTypeRepository;
        }
        /// <summary>
        /// 到货类型业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(ArrivalTypeQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result();
            try
            {
                var arrivalTypeList = await (await _arrivalTypeRepository.GetAll()).Where(c => c.PId == 0).ToListAsync();
                List<PermissionCascaderDto> dtos = new List<PermissionCascaderDto>();
                foreach (var item in arrivalTypeList)
                {
                    PermissionCascaderDto permissionCascader = new PermissionCascaderDto();
                    permissionCascader.label = item.ArrivalTypeName;
                    permissionCascader.value = item.ArrivalTypeId;
                    permissionCascader.children = await GetCascaders(item.ArrivalTypeId);
                    dtos.Add(permissionCascader);
                }
                result.Data = dtos;

            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
        public async Task<List<PermissionCascaderDto>> GetCascaders(int pid = 0)
        {
            var list = await (await _arrivalTypeRepository.GetAll()).Where(c => c.PId == pid).ToListAsync();
            List<PermissionCascaderDto> dtos = new List<PermissionCascaderDto>();
            foreach (var item in list)
            {
                PermissionCascaderDto permissionCascader = new PermissionCascaderDto();
                permissionCascader.label = item.ArrivalTypeName;
                permissionCascader.value = item.ArrivalTypeId;
                permissionCascader.children = await GetCascaders(item.ArrivalTypeId);
                dtos.Add(permissionCascader);
            }
            return dtos;
        }
    }
}
